import React, { useEffect, useState, useRef } from 'react'
import { Button, Space, Steps, Card, Typography, Modal, Row, Col, message } from "antd";
import { getActivityTypeCode } from "@/utils/tools.js"
import { getOrderLogisticsDetail, expressageCompanySettingList, apiDeliverymanPage } from '@/api/fundsManage/billList.js';
import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-components';
import { getDateTime2 } from '@/utils/getTimes'
import { apiSendOrders, apiShopOrderDetail } from "@/api/orderManage";

const { Step } = Steps;
const { Paragraph } = Typography;
const OrderStep = (props) => {
  const data = props.orderInfo // 组件传参
  const formRef = useRef()
  const [stepCurrentValue, setStepCurrentValue] = useState(null) //当前步骤
  const [stepData, setStepData] = useState([]) // 步骤数据
  const [logisticsModal, setLogisticsModal] = useState(false) //查看物流弹窗
  const [logisticsData, setLogisticsData] = useState([]) //物流详情
  const [courierCode, setCourierCode] = useState([]) //物流详情
  const [courierNo, setCourierNo] = useState([]) //物流详情
  const [options, setOptions] = useState([]) //快递公司
  const [courierOptions, setCourierOptions] = useState([])
  const [sendModal, setSendModal] = useState(false)
  const [off, setOff] = useState(1)
  const [upDate, setUpDate] = useState(0) //更新快递公司
  const formItemLayout = {
    labelCol: { span: 6 },
    wrapperCol: { span: 18 },
  }

  useEffect(() => {
    expressageCompanyData()
    getCourierOptions()
    getData()
  }, [upDate])

  //快递公司数据处理
  const expressageCompanyData = async () => {
    let res = await expressageCompanySettingList()
    if (res.code === 0 && res.data) {
      let data = res.data.map(v => {
        return {
          value: v.expressageCompanyCode,
          label: v.expressageCompanyName
        }
      })
      setOptions(data)
      setUpDate(2)
    }
  }
  // 配送员列表
  let getCourierOptions = async () => {
    let res = await apiDeliverymanPage({ pageNo: 1, pageSize: -1 })
    if (res.code === 0 && res.data) {
      let courierOptions = []
      res.data.map(v => {
        if (v.hasBoundCar) {
          courierOptions.push({
            value: v.deliverymanId,
            label: v.name
          })
        }
      })
      setCourierOptions(courierOptions)
    }
  }
  //处理数据
  const getData = async () => {
    data.activityTypeCode = getActivityTypeCode(props.orderInfo.activityTypeCode) //订单类型
    setStepCurrentValue(data.orderState)
    data.orderState !== '0' ? getFinishStep(data) : getOffStep(data)
  }
  // step交易完成进度数据处理
  const getFinishStep = (params) => {
    if (params.orderState !== '0') {
      let step = ''
      switch (params.orderState) {
        case '3':
          step = 0
          break
        case '4':
          step = 1
          break
        case '5':
          step = 2
          break
        case '6':
          step = 1
          break
        case '9':
          step = 4
          break
      }
      setStepData([
        {
          title: '生成订单',
          description: params.createTime,
        },
        {
          title: params.orderState === '6' ? "待分享" : '已付款',
          description: params.orderState === '4' ? <Space direction='vertical'>
            <span>{params.payTime}</span>
            <Button onClick={() => toSend(data.shopOrderId)}>发货</Button>
          </Space> : params.payTime,

        },
        {
          title: '已发货',
          description: params.orderState === '5' ? <Space direction='vertical'>
            <span>{params.goodsGoTime}</span>
            <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
          </Space> : params.goodsGoTime,
        },
        {
          title: '交易完成',
          description: params.orderState === '9' ? <Space direction='vertical'>
            <span>{params.finishTime}</span>
            <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
          </Space> : params.finishTime
        },
      ])
      setStepCurrentValue(step)
    }
  }
  // step交易关闭进度数据处理
  const getOffStep = (params) => {
    let stepCurrent = ''
    let stepValue = []
    if (params.orderState === '0') {
      switch (params.beforeEndOrderState) {
        case '3':
          stepCurrent = 1
          stepValue = [
            {
              title: '生成订单',
              description: params.createTime,
            },
            {
              title: '交易关闭',
              description: params.orderEndTime,
            }
          ]
          break
        case '4':
          stepCurrent = 2
          stepValue = [
            {
              title: '生成订单',
              description: params.createTime,
            },
            {
              title: '已付款',
              description: params.payTime,
            },
            {
              title: '交易关闭',
              description: params.orderEndTime,
            }
          ]
          break
        case '5':
          stepCurrent = 3
          stepValue = [
            {
              title: '生成订单',
              description: params.createTime,
            },
            {
              title: '已付款',
              description: params.payTime,
            },
            {
              title: '已发货',
              description: params.orderState === '5' ? <Space direction='vertical'>
                <span>{params.goodsGoTime}</span>
                <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
              </Space> : params.goodsGoTime
            },
            {
              title: '交易关闭',
              description: (
                <Space direction='vertical'>
                  <span>{params.orderEndTime}</span>
                  <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
                </Space>
              ),
            }
          ]
          break
        case '9':
          stepCurrent = 4
          stepValue = [
            {
              title: '生成订单',
              description: params.createTime,
            },
            {
              title: '已付款',
              description: params.payTime,
            },
            {
              title: '已发货',
              description: params.orderState === '5' ? <Space direction='vertical'>
                <span>{params.goodsGoTime}</span>
                <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
              </Space> : params.goodsGoTime
            },
            {
              title: '交易关闭',
              description: (
                <Space direction='vertical'>
                  <span>{params.orderEndTime}</span>
                  <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
                </Space>
              ),
            }
          ]
          break
        case '0':
          stepCurrent = 5
          stepValue = [
            {
              title: '生成订单',
              description: params.createTime,
            },
            {
              title: '已付款',
              description: params.payTime,
            },
            {
              title: '已发货',
              description: params.orderState === '5' ? <Space direction='vertical'>
                <span>{params.goodsGoTime}</span>
                <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
              </Space> : params.goodsGoTime
            },
            {
              title: '交易关闭',
              description: (
                <Space direction='vertical'>
                  <span>{params.orderEndTime}</span>
                  <Button onClick={() => checkLogistics(data.shopOrderId)}>查看物流</Button>
                </Space>
              ),
            }
          ]
          break
      }
      setStepCurrentValue(stepCurrent)
      setStepData(stepValue)
    }
  }

  const checkLogistics = async (orderId) => {
    let hqmzps = ""
    let res = await apiShopOrderDetail({ orderId })
    if (res.code === 0 && res.data.courierCode === "HQM") {
      hqmzps = "HQM"
    } else {
      hqmzps = ""
    }
    if (hqmzps === "HQM") {
      let context = null
      if (res.data.deliveryTask) {
        context = res.data.deliveryTask.hasOwnProperty('progressList') ? res.data.deliveryTask.progressList.map(v => {
          let time = v.createTime
          return {
            desc: v.progressDescription,
            time
          }
        }) : null
      }
      let courierCode = ""
      for (let i = 0; i < options.length; i++) {
        if (options[i].value === res.data.courierCode) {
          courierCode = options[i].label
        }
      }
      setLogisticsModal(true)
      setLogisticsData(context)
      setCourierCode(courierCode)
      setCourierNo(res.data.deliverymanName)
    } else {
      await getOrderLogisticsDetail(orderId).then(res => {
        if (res.code === 0 && res.data) {
          let context = null
          if (res.data.msg) {
            context = res.data.msg.hasOwnProperty('context') ? res.data.msg.context.map(v => {
              let time = v.time * 1000
              time = new Date(parseInt(time))
              time = getDateTime2(time)
              return {
                ...v,
                time
              }
            }) : null
          }
          let courierCode = ""
          for (let i = 0; i < options.length; i++) {
            if (options[i].value === res.data.courierCode) {
              // debugger
              courierCode = options[i].label
            }
          }
          // setTimeout(() => {
          setLogisticsModal(true)
          setLogisticsData(context)
          setCourierCode(courierCode)
          setCourierNo(res.data.courierNo)
          // }, 2000);
        }
      })
    }
  }

  const toSend = () => {
    setSendModal(true)
  }



  return (
    <div>
      <Paragraph>
        <blockquote>
          <Space size={30}>
            <span>订单号：{data.orderCode}</span>
            <span>下单时间：{data.createTime}</span>
            <span>{data.activityTypeCode}</span>
          </Space>
        </blockquote>
      </Paragraph>
      <Card>
        <Steps progressDot current={stepCurrentValue}>
          {
            stepData.map((item, index) => {
              return <Step title={item.title} subTitle={item.description} key={index} />
            })
          }
        </Steps>
      </Card>
      <Modal
        title={"跟踪物流"}
        open={logisticsModal}
        onCancel={() => { setLogisticsModal(false) }}
        onOk={() => { setLogisticsModal(false) }}
        cancelButtonProps={{ style: { display: "none" } }}
      >
        <p>快递公司：{courierCode}</p>
        {courierCode === "哈奇马自配送" ?
          <p>配送员：{courierNo}</p>
          : <p>快递单号：{courierNo}</p>
        }
        {
          logisticsData ? <Steps progressDot current={0} direction="vertical">
            {logisticsData.map((v, i) => {
              return <Step title={v.time} description={v.desc} key={i} />
            })}
          </Steps> : <p>暂无物流信息</p>
        }
      </Modal>
      <ModalForm
        title={"发货"}
        open={sendModal}
        {...formItemLayout}
        formRef={formRef}
        layout={'horizontal'}
        submitter={{
          render: (props, doms) => {
            return <Row>
              <Col span={22} offset={2}>
                <Space>{doms}</Space>
              </Col>
            </Row>
          },
        }}
        // onValuesChange={(changeValues) => console.log(changeValues)}
        onFinish={async (values) => {
          await apiSendOrders({ ...values, orderId: data.shopOrderId }).then((res) => {
            if (res.code === 0) {
              message.success('发货成功');
              setSendModal(false)
              setUpDate(1)
              props.getData()
            }
          })
        }}
        modalProps={{
          destroyOnClose: true,
          width: 400,
          onCancel: () => setSendModal(false),
        }}
        onFinishFailed={(values) => {
          if (values.errorFields.length) {
            message.error('请完善数据')
          }
        }}
        params={{}}
        request={async () => {
          // await waitTime(100);
          // 判断当前页面类型
          return {}
        }}
      >
        <ProFormSelect
          width="md"
          name="courierCode"
          label="快递公司"
          options={options}
          rules={[{ required: true, message: '请选择快递公司' }]}
          onChange={(e) => {
            if (e === "HQM") {
              setOff(2)
            } else {
              setOff(1)
            }
          }}
        />
        {
          off === 1 ?
            <ProFormText
              width="md"
              name="courierNo"
              label="快递单号"
              rules={[{ required: true, message: '请输入快递单号' }]}
            />
            : <ProFormSelect
              width="md"
              name="deliverymanId"
              label="配送员"
              options={courierOptions}
              rules={[{ required: true, message: '请选择配送员' }]}
            />
        }
      </ModalForm>
    </div >
  )
}

export default OrderStep;
